package com.project.handler;

import com.project.AOP.AopConfig;
import com.project.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.project.handler
 * Description: 自定义异常处理器
 *              使用异常处理器进行全局异常捕获
 *
 * @Author 看到风
 * @Create 2023/10/19 21:01
 * @Version 1.0
 */
@ControllerAdvice(annotations = {RestController.class, Component.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    //进行异常处理方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg=split[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler(SecurityException.class)
    public R<String> AopConfigHandler(SecurityException ex) {
        return R.error("权限不足");
    }
}
